<?php

/**
 * Capital Direct Lending (http://www.philbsd.com/cdl)
 *
 * Copyright (C) 2008 Philippine Business Solution Developers <http://www.philbsd.com>
 * All rights reserved.
 *
 *
 * LICENSE
 *
 * This source file is subject to the GNU General Public License v3 license
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@philbsd.com so we can send you a copy immediately.
 *
 * @copyright  (c) 2008 Philippine Business Solution Developers. (http://www.philbsd.com)
 * @license    http://www.gnu.org/licenses/gpl-3.0.txt
 * @version    $Id: RoleController.php 42 2008-03-12 10:05:35Z philbsd $
 */

class RoleController extends Philbsd_Controller_Action
{
    protected $_session;

	protected $_tableInstance;

    public function init()
    {
        $this->_session = new Zend_Session_Namespace(__CLASS__);
		$this->_tableInstance = new Philbsd_Model_Roles();
    }

    public function indexAction()
    {
		$roles = array();
		$roleRowSet = $this->_tableInstance->fetchAll();
		while ($roleRow = $roleRowSet->current()) {
			$role = $roleRow->toArray();
			$roles[] = $role;
			$roleRowSet->next();
		}
		$this->view->records = $roles;

		if (isset($this->_session->message)) {
			$this->view->message = $this->_session->message;
			unset($this->_session->message);
		}

		$this->render();
    }

	public function viewAction()
	{
		$params = $this->getRequest()->getUserParams();
		if (!isset($params['id'])) {
			$this->_redirect('admin/role');
		}
		$roleRowSet = $this->_tableInstance->find($params['id']);
		$roleRow = $roleRowSet->current();
		$role = $roleRow->toArray();

		$this->view->record = $role;
		$this->render();
	}

	public function addAction()
	{
		if (isset($_POST['btnCancel'])) {
			$this->_redirect('admin/role');
		}
		$roleRow = $this->_tableInstance->createRow();

		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			$messages = array();

		    $filters = array(
			    'name' => 'StringTrim',
			    );

    		$validators = array(
	    		'name' => array(
		    		array('StringLength', 3, 64),
			    	'messages' => array(
				    	'Name must be between %min% and %max% characters in length'
					    )
    				),
			);

		    $input = new Zend_Filter_Input($filters, $validators, $_POST);

			if (!$input->isValid()) {
				$messages = $input->getMessages();
			}

			if ($this->_tableInstance->fetchRow("name = '" . $input->getUnescaped('name') . "'")) {
				$messages[] = array('name'=>"Name already exists.");
			}

			if (!$messages) {
				$roleRow->name = $input->getUnescaped('name');
				$roleRow->super_user = isset($_POST['super_user'])? 1 : 0;
				$roleRow->description = $_POST['description'];

				if ($id = $roleRow->save()) {
					$this->_session->message = "Id#{$id} added successfully";
					$this->_redirect('admin/role');
				} else {
					$messages[] = array('add'=>"Failed to add.");
				}

	            $this->_redirect('admin/role');
			}
			$this->view->messages = $messages;
		}

		$this->render();
	}

	public function editAction()
    {
		if (isset($_POST['btnCancel'])) {
			$this->_redirect('admin/role');
		}
		$params = $this->getRequest()->getUserParams();

		if (!isset($params['id'])) {
			$this->_redirect('admin/role');
		}

		$roleRowSet = $this->_tableInstance->find($params['id']);
		if (!($roleRow = $roleRowSet->current())) {
			$this->_redirect('admin/role');
		}

		$this->view->record = $roleRow->toArray();

		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			$messages = array();

		    $filters = array(
			    'name' => 'StringTrim',
			    );

    		$validators = array(
	    		'name' => array(
		    		array('StringLength', 3, 64),
			    	'messages' => array(
				    	'Name must be between %min% and %max% characters in length'
					    )
    				),
			);

		    $input = new Zend_Filter_Input($filters, $validators, $_POST);

			if (!$input->isValid()) {
				$messages = $input->getMessages();
			}

			if ($roleRow->name != $input->getUnescaped('name') &&
                $this->_tableInstance->fetchRow("name = '" .
                $input->getUnescaped('name') . "'")) {
				$messages[] = array('name'=>"Name already exists.");
			}

			if (!$messages) {
				$roleRow->name = $input->getUnescaped('name');
				$roleRow->super_user = isset($_POST['super_user'])? 1 : 0;
				$roleRow->description = $_POST['description'];

				if ($roleRow->save() == $params['id']) {
					$this->_session->message = "Id#{$params['id']} updated successfully";
					$this->_redirect('admin/role');
				} else {
					$messages[] = array('add'=>"Failed to update.");
				}

	            $this->_redirect('admin/role');
			}
			$this->view->messages = $messages;
		}

        $this->render();
    }

	public function deleteAction()
	{
		if (isset($_POST['btnCancel'])) {
			$this->_redirect('admin/role');
		}
		$params = $this->getRequest()->getUserParams();

		if (!isset($params['id'])) {
			$this->_redirect('admin/role');
		}
		$roleRowSet = $this->_tableInstance->find($params['id']);
		if (!$roleRow = $roleRowSet->current()) {
			$this->_session->message = "Id#{$params['id']} does not exists.";
            $this->_redirect('admin/role');
		}

		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			$roleRow->delete();
			$this->_session->message = "Id#{$params['id']} deleted successfully";
            $this->_redirect('admin/role');
		}

		$role = $roleRow->toArray();

		$this->view->record = $role;
		$this->render();
	}

	public function privilegeAction()
	{
		if (isset($_POST['btnCancel'])) {
			$this->_redirect('admin/role');
		}
		$params = $this->getRequest()->getUserParams();

		if (!isset($params['id'])) {
			$this->_redirect('admin/role');
		}
		$roleRowSet = $this->_tableInstance->find($params['id']);
		if (!$roleRow = $roleRowSet->current()) {
			$this->_session->message = "Id#{$params['id']} does not exists.";
            $this->_redirect('admin/role');
		}
		$record = $roleRow->toArray();
		if ($parentRoleRow = $roleRow->findParentRow('Philbsd_Model_Roles')) {
			$record['parent'] = $parentRoleRow->toArray();
		}

		$aclList = array();
		$aclTable = new Philbsd_Model_Acl();
		$aclRowSet = $aclTable->fetchAll("role_id = {$params['id']}");
		while ($aclRow = $aclRowSet->current()) {
			$aclList[$aclRow->module_resource_privilege_id] = $aclRow->toArray();
			$aclRowSet->next();
		}
		$this->view->aclList = $aclList;

		$moduleResourcePrivilegeTable = new Philbsd_Model_Module_Resource_Privileges();

		$this->view->record = $record;

		$records = array();
		$moduleResourceTable = new Philbsd_Model_Module_Resources();
		$moduleResourceRowSet = $moduleResourceTable->fetchAll();
		while ($moduleResourceRow = $moduleResourceRowSet->current()) {
			$record[$moduleResourceRow->module_id] = $moduleResourceRow->toArray();

			$moduleRow = $moduleResourceRow->findParentRow('Philbsd_Model_Modules');
			$records[$moduleResourceRow->module_id] = $moduleRow->toArray();

			$resourceRow = $moduleResourceRow->findParentRow('Philbsd_Model_Resources');

			$resources = $resourceRow->toArray();
			$moduleResourcePrivilegeRowSet = $moduleResourcePrivilegeTable->fetchAll("module_resource_id = {$moduleResourceRow->id}");
			while ($moduleResourcePrivilegeRow = $moduleResourcePrivilegeRowSet->current()) {
				$privilegeRow = $moduleResourcePrivilegeRow->findParentRow('Philbsd_Model_Privileges');
				$resources['privileges'][$moduleResourcePrivilegeRow->id] = $privilegeRow->toArray();
				$moduleResourcePrivilegeRowSet->next();
			}
			$moduleResources[$moduleResourceRow->id] = $moduleResourceRow->toArray();

			$records[$moduleResourceRow->module_id]['resources'][] = $resources;

			$moduleResourceRowSet->next();
		}

		$this->view->records = $records;
		$this->render();
	}

}
